<%@ page language="java" import="com.alibaba.fastjson.JSONObject" pageEncoding="UTF-8" %>
<%@ page import="okhttp3.*" %>
<%@ page import="org.apache.axis.encoding.Base64" %>
<%@ page import="org.apache.http.conn.ssl.AllowAllHostnameVerifier" %>
<%@ page import="org.dom4j.Document" %>
<%@ page import="org.dom4j.DocumentHelper" %>
<%@ page import="org.dom4j.Element" %>
<%@ page import="weaver.alioss.AliOSSObjectManager" %>
<%@ page import="weaver.alioss.AliOSSObjectUtil" %>
<%@ page import="weaver.conn.ConnStatement" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.file.AESCoder" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.concurrent.TimeUnit" %>
<%@ page import="java.util.zip.ZipInputStream" %>
<%--流程退回调用QMS接口--%>
<%
    String docid = Util.null2String(request.getParameter("docid"));
    try {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select imagefileid,imagefilename from DocImageFile where docid in (" + docid + ")");
        while (rs.next()) {
            int imagefileid = Util.getIntValue(rs.getString("imagefileid"), -1);
            String imagefilename = Util.null2String(rs.getString("imagefilename"));
            out.print(">>>>>>jsonData>>>>>imagefilename=" + imagefilename + "<br/>");
            out.print(">>>>>>jsonData>>>>>imagefileid=" + imagefileid + "<br/>");
            try {
                InputStream inputStream = getInputStreamById(imagefileid);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024*10]; // 或者根据实际情况选择合适的缓冲区大小
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }
                byteArrayOutputStream.flush();
                JSONObject jsonData = new JSONObject();
                jsonData.put("ParentObjectID", "9BFD4E78D6011EDE9EAA3F5AF023F999");
                jsonData.put("ContractID", "272");
                jsonData.put("TypeCode", "10001");
                jsonData.put("MimeType", "application/pdf");
                jsonData.put("Binary", byteArrayOutputStream.toByteArray());
                jsonData.put("Name", imagefilename);
                jsonData.put("CategoryCode","2");
                out.print(">>>>>>jsonData>>>>>" + jsonData.toJSONString() + "<br/>");
                JSONObject resultJson  = sendPostOKHttpRequest(jsonData.toJSONString());
                out.print(">>>>>>resultJson>>>>>" + resultJson + "<br/>");
            } catch (Exception e) {
                out.println(">>>>>测试接口异常！！！"+e);
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        out.println(">>>>>测试接口异常！！！");
        e.printStackTrace();
    }

%>
<%!
    private static BaseBean baseBean = new BaseBean();
    private static final String URL = baseBean.getPropValue("zhlxc4", "url");
    private static final String USERNAME = baseBean.getPropValue("zhlxc4", "username");
    private static final String PASSWORD = baseBean.getPropValue("zhlxc4", "password");

    //返回文件流   已经经过脱密、解压
    public static InputStream getInputStreamById(int imageFileId) {
        InputStream imagefile = null;
        try {
            RecordSet rs = new RecordSet();
            String sql = "select fileRealPath,isZip,isaesencrypt,aescode,tokenKey,storageStatus  from ImageFile where imageFileId =?";
            rs.executeQuery(sql,imageFileId);
            if (rs.next()) {
                String static_fileRealPath = Util.null2String(rs.getString("fileRealPath"));
                String static_isZip = Util.null2String(rs.getString("isZip"));
                int static_isaesencrypt = Util.getIntValue(rs.getString("isaesencrypt"), 0);
                String static_aescode = Util.null2String(rs.getString("aescode"));
                String static_tokenKey = Util.null2String(rs.getString("tokenKey"));
                String static_storageStatus = Util.null2String(rs.getString("storageStatus"));
                boolean isonlyAliOSS = false;
                if (!static_tokenKey.equals("") && static_storageStatus.equals("1") && AliOSSObjectManager.isonlyAliOSS()) {
                    isonlyAliOSS = true;
                }

                if (isonlyAliOSS) {
                    imagefile = AliOSSObjectUtil.downloadFile(static_tokenKey);
                } else {
                    if (static_fileRealPath != null && !static_fileRealPath.equals("")) {
                        File thefile = new File(static_fileRealPath);
                        if (static_isZip.equals("1")) {
                            ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile));
                            if (zin.getNextEntry() != null) {
                                imagefile = new BufferedInputStream(zin);
                            }
                        } else {
                            imagefile = new BufferedInputStream(new FileInputStream(thefile));
                        }
                    } else {
                        ConnStatement statement = null;
                        try {
                            statement = new ConnStatement();
                            boolean isoracle = ("oracle").equals(statement.getDBType());
                            statement.setStatementSql("select imagefile from ImageFile where imagefileid = " + imageFileId);
                            statement.executeQuery();
                            if (statement.next()) {
                                if (isoracle) {
                                    imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile"));
                                } else {
                                    imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile"));
                                }
                            }
                        } catch (Exception ex) {
                        } finally {
                            try {
                                if (statement != null) {
                                    statement.close();
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                    if (static_isaesencrypt == 1) {
                        imagefile = AESCoder.decrypt(imagefile, static_aescode);
                    }

                }
            }


        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return imagefile;
    }

    private static JSONObject sendPostOKHttpRequest(String params) {
        String apiType = "/sap/c4c/odata/v1/c4codataapi/ContractAttachmentFolderCollection";
        JSONObject resultJson = new JSONObject();
        String code = "fail";
        String message = "";
        String apiUrl = URL + Util.null2String(apiType);
        try {
            String authorization = " Basic " + Base64.encode((USERNAME + ":" + PASSWORD).getBytes());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .hostnameVerifier(new AllowAllHostnameVerifier())
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Authorization", authorization)
                    .build();
            Response response = client.newCall(request).execute();
            int responeCode = response.code();
            if (responeCode == 201) {
                String responseStr = Util.null2String(response.body().string());
                try {
                    Document xmlDocument = DocumentHelper.parseText(responseStr);
                    if (xmlDocument != null) {
                        Element rootElement = xmlDocument.getRootElement();
                        Element content = rootElement.element("content");
                        Element properties = content.element("properties");
                        Element ObjectID = properties.element("ObjectID");
                        resultJson.put("data", ObjectID.getTextTrim());
                        code = "success";
                        message = "调用成功";
                    }
                } catch (Exception e) {
                    message = "调用成功，返回的XML格式异常";
                }
            } else {
                message = "调用失败，响应码=" + responeCode;
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("message", message);
        return resultJson;
    }

%>



